<template>
  <div class="personnel-management">
    <h1 class="page-title">警员管理</h1>
    <div class="action-bar">
      <button class="btn btn-primary" @click="openAddModal">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
        <span>添加警员</span>
      </button>
      <button class="btn btn-secondary" @click="triggerImport">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
          <polyline points="17 8 12 3 7 8"></polyline>
          <line x1="12" y1="3" x2="12" y2="15"></line>
        </svg>
        <span>导入警员信息</span>
      </button>
      <input type="file" ref="fileInput" @change="handleFileImport" accept=".xls,.xlsx" style="display: none;" />
      <button class="btn btn-secondary" @click="exportToExcel">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
          <polyline points="7 10 12 15 17 10"></polyline>
          <line x1="12" y1="15" x2="12" y2="3"></line>
        </svg>
        <span>导出警员清单</span>
      </button>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else class="table-container">
      <table>
        <thead>
        <tr>
          <th>警员编号</th>
          <th>姓名</th>
          <th>部门</th>
          <th>联系方式</th>
          <th>专业技能</th>
          <th>培训记录</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-if="paginatedList.length === 0">
          <td colspan="7" class="empty-data">暂无数据</td>
        </tr>
        <tr v-for="officer in paginatedList" :key="officer.officerId">
          <td>{{ officer.officerNumber }}</td>
          <td>{{ officer.name }}</td>
          <td>{{ officer.department }}</td>
          <td>{{ officer.phone }}</td>
          <td>{{ officer.skills }}</td>
          <td>{{ officer.trainingRecord }}</td>
          <td>
            <button class="btn-action btn-edit" @click="openEditModal(officer.officerId)">编辑</button>
            <button class="btn-action btn-delete" @click="deleteOfficer(officer.officerId)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 导入进度条 -->
    <div v-if="importing" class="import-progress-container">
      <div class="import-progress-bar" :style="{ width: `${importProgress.valueOf() / totalItems.valueOf() * 100}%` }"></div>
      <span>{{ importProgress.valueOf() }}/{{ totalItems.valueOf() }} 条已导入</span>
    </div>

    <Pagination
      v-if="policeList.length > itemsPerPage"
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-changed="handlePageChange"
    />

    <PersonnelFormModal
      v-if="isModalOpen"
      :is-edit-mode="isEditMode"
      :initial-data="selectedOfficer"
      @close="closeModal"
      @save="saveOfficer"
    />
    <SuccessPopup ref="successPopup" />
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import PersonnelFormModal from './PersonnelFormModal.vue';
import Pagination from '@/components/Pagination.vue';
import * as XLSX from 'xlsx';
import api from '@/utils/axios';
import SuccessPopup from '@/components/common/SuccessPopup.vue';
import { ElNotification, ElMessageBox } from 'element-plus';

const API_BASE_URL = 'http://localhost:8080/api/auth';
const successPopup = ref(null);

const policeList = ref<any[]>([]);
const loading = ref(false);
const errorMessage = ref('');
const importing = ref(false);
const importProgress = ref(0);
const totalItems = ref(0);

const currentPage = ref(1);
const itemsPerPage = ref(10);
const totalPages = computed(() => Math.ceil(policeList.value.length / itemsPerPage.value));
const paginatedList = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  return policeList.value.slice(start, end);
});
const handlePageChange = (page: number) => { currentPage.value = page; };

const isModalOpen = ref(false);
const isEditMode = ref(false);
const selectedOfficer = ref<any>(null);
const fileInput = ref<HTMLInputElement | null>(null);

onMounted(() => {
  fetchAllOfficers();
});

const fetchAllOfficers = async () => {
  try {
    loading.value = true;
    errorMessage.value = '';
    const response = await api.get(`${API_BASE_URL}/officers`);
    policeList.value = response.data.data;
  } catch (error: any) {
    errorMessage.value = `获取警员数据失败: ${error.response?.data?.message || error.message}`;
    console.error('Fetch officers error:', error);
  } finally {
    loading.value = false;
  }
};

const openAddModal = () => {
  isEditMode.value = false;
  selectedOfficer.value = null;
  isModalOpen.value = true;
};

const openEditModal = async (officerId: number) => {
  try {
    loading.value = true;
    errorMessage.value = '';
    const response = await api.get(`${API_BASE_URL}/officers/${officerId}`);
    isEditMode.value = true;
    selectedOfficer.value = { ...response.data, officerId: response.data.officerId };
    isModalOpen.value = true;
  } catch (error: any) {
    errorMessage.value = `获取警员详情失败: ${error.response?.data?.message || error.message}`;
    console.error('Fetch officer detail error:', error);
  } finally {
    loading.value = false;
  }
};

const closeModal = () => {
  isModalOpen.value = false;
};

const saveOfficer = async (data: any) => {
  try {
    loading.value = true;
    errorMessage.value = '';
    let response;

    if (isEditMode.value) {
      response = await api.put(`${API_BASE_URL}/officers/${data.officerId}`, {
        name: data.name,
        department: data.department,
        phone: data.phone,
        skills: data.skills,
        trainingRecord: data.trainingRecord,
        officerNumber: data.officerNumber
      });
    } else {
      response = await api.post(`${API_BASE_URL}/officer`, {
        officerNumber: data.officerNumber,
        name: data.name,
        department: data.department,
        phone: data.phone,
        skills: data.skills,
        trainingRecord: data.trainingRecord
      });
    }

    fetchAllOfficers();
    closeModal();
  } catch (error: any) {
    errorMessage.value = `保存警员失败: ${error.response?.data?.message || error.message}`;
    console.error('Save officer error:', error);
  } finally {
    loading.value = false;
  }
};

const deleteOfficer = async (id: string) => {
  if (confirm(`确定要删除警员 ${id} 的信息吗？`)) {
    try {
      loading.value = true;
      errorMessage.value = '';
      await api.delete(`${API_BASE_URL}/deleteOfficer/${id}`);
      fetchAllOfficers();
      if (paginatedList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
      }
    } catch (error: any) {
      errorMessage.value = `删除警员失败: ${error.response?.data?.message || error.message}`;
      console.error('Delete officer error:', error);
    } finally {
      loading.value = false;
    }
  }
};

const triggerImport = () => { fileInput.value?.click(); };

const handleFileImport = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (!target.files || target.files.length === 0) return;

  const file = target.files[0];
  console.log('Selected file:', file);  // 打印选择的文件

  if (!file.name.endsWith('.xls') && !file.name.endsWith('.xlsx')) {
    ElNotification({
      title: '错误',
      message: '请上传Excel文件（.xls或.xlsx格式）',
      type: 'error',
      duration: 3000
    });
    if (fileInput.value) fileInput.value.value = '';
    return;
  }

  try {
    importing.value = true;
    loading.value = true;
    errorMessage.value = '';

    // 读取文件内容
    const fileData = await readFileAsArrayBuffer(file);
    if (!fileData) {
      throw new Error('文件读取失败');
    }
    console.log('File data read successfully:', fileData);  // 打印文件读取的内容

    const workbook = XLSX.read(fileData, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    console.log('Parsed JSON Data:', jsonData);  // 打印解析后的数据

    if (jsonData.length === 0) {
      throw new Error('Excel文件中没有数据');
    }

    // 调用导入警员数据处理函数
    await importOfficers(jsonData); // <-- 在这里调用 importOfficers

  } catch (error) {
    console.error('Error during file import:', error);
    errorMessage.value = `导入失败: ${error.message}`;
  } finally {
    loading.value = false;
    importing.value = false;
    if (fileInput.value) fileInput.value.value = '';
  }
};



const generatePreviewHtml = (data: any[]) => {
  if (data.length === 0) return '<div>无数据</div>';

  const headers = Object.keys(data[0]);
  const previewData = data.slice(0, 5); // 只显示前5条数据预览

  let html = '<div style="max-height: 300px; overflow-y: auto; text-align: left; font-size: 14px;">';
  html += '<table border="1" cellpadding="8" style="width: 100%; border-collapse: collapse;">';
  html += '<thead><tr>';
  headers.forEach(header => html += `<th style="background-color: #f0f0f0; padding: 8px; text-align: left;">${header}</th>`);
  html += '</tr></thead><tbody>';

  previewData.forEach((item, index) => {
    html += '<tr>';
    headers.forEach(header => {
      html += `<td style="padding: 8px; border: 1px solid #ddd;">${item[header] || '-'}</td>`;
    });
    html += '</tr>';
  });

  html += '</tbody></table>';
  if (data.length > 5) {
    html += `<div style="margin-top: 10px; color: #666;">... 剩余 ${data.length - 5} 条数据</div>`;
  }
  html += '</div>';
  return html;
};

const readFileAsArrayBuffer = (file: File): Promise<ArrayBuffer | null> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      if (e.target?.result) {
        resolve(e.target.result as ArrayBuffer);
      } else {
        resolve(null);
      }
    };
    reader.onerror = (e) => {
      console.error('File read error:', e);
      resolve(null);
    };
    reader.readAsArrayBuffer(file);
  });
};

const importOfficers = async (officerDataList: any[]) => {
  try {
    // 数据映射与转换
    const formattedData = officerDataList.map(item => ({
      officerNumber: item['警员编号'],
      name: item['姓名'],
      department: item['部门'],
      phone: item['联系方式'] || '',
      skills: item['专业技能'] || '',
      trainingRecord: item['培训记录'] || ''
    }));

    console.log('Formatted Data:', formattedData);  // 检查数据

    // 初始化导入进度
    totalItems.value = formattedData.length;
    importProgress.value = 0;

    // 逐条导入
    for (const item of formattedData) {
      console.log('Importing:', item);  // 确保每条数据被处理
      try {
        // 调用后端接口逐条插入警员数据
        await api.post(`${API_BASE_URL}/officer`, item);
        importProgress.value++;
      } catch (error: any) {
        console.error(`导入警员 ${item.officerNumber} 失败`, error);
      }
    }

    console.log('Import progress:', importProgress.value);  // 进度是否正常更新

    // 刷新数据
    await fetchAllOfficers();

    if (successPopup.value) {
      successPopup.value.triggerSuccessPopup(totalItems.value); // 显示成功弹窗
    }

  } catch (error: any) {
    errorMessage.value = `导入失败: ${error.message}`;
    ElNotification({
      title: '错误',
      message: errorMessage.value,
      type: 'error',
      duration: 5000
    });
    console.error('Import error:', error);
  } finally {
    loading.value = false;
    importing.value = false;
    if (fileInput.value) fileInput.value.value = '';
    totalItems.value = 0;
    importProgress.value = 0;
  }
};



const generateErrorLog = (invalidItems: any[]) => {
  const errorLog = ['=== 导入数据错误日志 ==='];
  invalidItems.forEach(item => {
    errorLog.push(`第 ${item.index + 2} 行 (警员编号: ${item.data?.officerNumber || '未知'}): ${item.error}`);
  });
  errorLog.push('=== 请修正后重新导入 ===');

  const blob = new Blob([errorLog.join('\n')], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = '警员导入错误日志.txt';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  return errorLog.join('\n');
};

const exportToExcel = () => {
  const headerMap = {
    officerNumber: '警员编号', name: '姓名', department: '部门', phone: '联系方式',
    skills: '专业技能', trainingRecord: '培训记录'
  };
  const dataToExport = policeList.value.map(officer => ({
    [headerMap.officerNumber]: officer.officerNumber, [headerMap.name]: officer.name,
    [headerMap.department]: officer.department, [headerMap.phone]: officer.phone,
    [headerMap.skills]: officer.skills, [headerMap.trainingRecord]: officer.trainingRecord,
  }));
  const worksheet = XLSX.utils.json_to_sheet(dataToExport);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '警员清单');
  XLSX.writeFile(workbook, '警员信息清单.xlsx');
};
</script>
<style>
@import "@/assets/styles/views/admin/PersonnelManagement.css";
.import-progress-container {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
}
.import-progress-bar {
  flex: 1;
  height: 16px;
  background-color: #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 10px;
}
.import-progress-bar::before {
  content: '';
  display: block;
  height: 100%;
  background-color: #409EFF;
  width: 0;
  transition: width 0.3s ease;
}

</style>
